const router = require('koa-router')()
const db = require('../utils/mysql.js');
const config  = require('../../config')[process.env.NODE_ENV];
router.get('/list', async ctx=>{
  const zone = ctx.query.zone
  const r = await queryCarList(zone)
  ctx.body={'err':0,'list':r}
});
router.get('/getallinfo', async ctx=>{
  const r = await queryCarStatus()
  ctx.body={'err':0,'list':r}
});
router.get('/getinfobyid', async ctx=>{
  // const r = await queryCarStatus()
  ctx.body={'err':0}
});

async function queryCarList(zone){
  let sql = "select id,code,price,x,y,extra_info extraInfo from bxc_car_"+config.tt;
  if(zone){
    sql += " where zone=:zone"
  }
  const res = await db.query(sql,{'zone':zone});
  return res;
}

async function queryCarStatus(){
	let sql = "select a.id,a.code ,a.status,a.zone rem,a.price price, ifnull( b.num ,0) soldNum,ifnull(c.num,0) xkNum from bxc_car_"
  +config.tt+" a left join (select car_id,count(user_id) num from  hrc_car_sold_"
  +config.tt+" group by car_id) b on a.id = b.car_id left join (select code,count(id) num from  hrs_xk_"
  +config.tt+" group by code) c on a.code = c.code"

	const res = await db.query(sql);
  return res;
}
module.exports = router;
